import fire
import chevron
import json
import os
import sys
import codecs
import requests
import yaml
import knife
from termcolor import cprint

yaml.warnings({'YAMLLoadWarning':False}) 

def pipenv(mirror="aliyun"):
    """ 
    me pipenv
    """
    with codecs.open("Pipfile", 'r', encoding='utf-8') as f:
        content = f.read()
        content = content.replace("https://pypi.org/simple","https://mirrors.aliyun.com/pypi/simple/")
        content = content.replace("pypi","aliyun")
    with codecs.open("Pipfile", 'w', encoding='utf-8') as f:
        f.write(content)
    return "pypi use " + mirror

def jpg(dir_or_file=os.getcwd()):
    """ 
    me jpg 
    """
    knife.to_jpg(dir_or_file)
    return "ok"


def png(dir_or_file=os.getcwd()):
    """ 
    me png 
    """
    knife.to_png(dir_or_file)
    return "ok"

def to(url="http://www.baidu.com/"):
    """ 
    me to calc
    me to http://www.github.com/
    """
    return cmd("start "+url)

def calc():
    """ 
    me calc
    """
    print("打开计算器")
    return to("calc ")

def hello(name):
    """ 
    me hello east196
    """
    return 'hello {name}!'.format(name=name)

def path():
    cprint(os.getcwd(),"green")
    cprint(current_src_dir(),"red")

def cwd():
    cwd = os.getcwd()
    print(cwd)
    print(os.path.basename(cwd))
    print(os.path.dirname(cwd))
    return os.path.basename(cwd)

def cmd(command="http http://httpbin.org/get"):
    """ 
    me cmd "{'name':'tom','age':'22'}"
    """
    d=os.popen(command)
    f=d.read()
    d.close()
    return f

def cmds(*commands):
    for command in commands:
        print(command)
        f=cmd(command)
        print(f)

def git(command="init",msg="init"):
    """ 
    me git
    me git init
    me git push "+ pull"
    me git pull
    me git log
    """
    if "init" == command: # 注意有.git就会直接提交
        commands = [
        "git init",
        "git add .",
        'git commit -m "'+msg+'"',
        "git remote add origin https://gitee.com/east196/"+cwd()+".git",
        "git push -u origin master",
        ]
        cmds(*commands)
        return
    if "push" == command:
        commands = [
        "git add .",
        'git commit -m "'+msg+'"',
        "git push",
        ]
        cmds(*commands)
        return
    if "pull" == command:
        command = "git pull"
    if "log" == command:
        command = "git log --oneline"
    f=cmd(command)
    return f

def post(data={'name':'tom','age':'22'},url='http://httpbin.org/post'):
    """ 
    me post "{'name':'tom','age':'22'}"
    """
    response = requests.post(url, json=data)
    return response.text

def get(data={'name':'tom','age':'22'},url='http://httpbin.org/get'):
    """ 
    me get "{'name':'tom','age':'22'}"
    """
    response = requests.get(url, params=data)
    return response.text

def yml(cfgfile):
    """ 
    me yml cfg.yml
    """
    with codecs.open(cfgfile,'r',encoding='utf-8') as f:
        cfg=f.read()
        knife.highlight(cfg,"yaml")
        d=yaml.load(cfg, Loader=yaml.FullLoader)
        knife.highlight(json.dumps(d, ensure_ascii=True,indent=2),"json")


def mustache(args):
    """ 
    me mustache "{'template':'hello {{name}}!','data':{'name':'east'}}"
    """
    return chevron.render(**args)

def current_src_dir():
    return os.path.split(os.path.realpath(__file__))[0]

def tpl(name,path_template, path_data, content_data):
    """ 
    me tpl "{{maven_project}}/pom.xml" "{'maven_project': 'hello_maven'}" "{'name': 'east'}"
    """
    # print(path_template, path_data, content_data)
    t = os.path.join(current_src_dir(),"templates",name,path_template)
    # print(current_src_dir(),"templates",name,path_template,t)
    with codecs.open(t, "r", encoding='utf-8') as f:
        content_template = f.read()
    path_args = {'template': path_template, 'data': path_data}
    content_args = {'template': content_template, 'data': content_data}
    path, content = chevron.render(**path_args), chevron.render(**content_args)
    rpath = os.path.join(os.getcwd(),path.replace(".mustache",""))
    dir,_ = os.path.split(rpath)
    if not os.path.exists(dir):
        os.makedirs(dir)
    with codecs.open(rpath, 'w', encoding='utf-8') as f:
        f.write(content)
    return rpath,content

def write(rpath,content):
    dir,_ = os.path.split(rpath)
    if not os.path.exists(dir):
        os.makedirs(dir)
    with codecs.open(rpath, 'w', encoding='utf-8') as f:
        f.write(content) 

def jfinal():
    """ 
    me jfinal
    """
    name="jfinal"
    d=cfg(name)
    d["project"]["group_path"]=os.path.sep.join(d["project"]["group"].split("."))
    tpl(name,"{{project.name}}/src/main/java/{{project.group_path}}/{{project.artifact}}/App.java.mustache",d,d)
    tpl(name,"{{project.name}}/src/main/java/{{project.group_path}}/{{project.artifact}}/AppConfig.java.mustache",d,d)
    tpl(name,"{{project.name}}/src/main/java/{{project.group_path}}/{{project.artifact}}/AppController.java.mustache",d,d)
    tpl(name,"{{project.name}}/src/main/resources/config.txt.mustache",d,d)
    tpl(name,"{{project.name}}/src/main/resources/log4j.properties.mustache",d,d)
    tpl(name,"{{project.name}}/src/test/java/{{project.group_path}}/{{project.artifact}}/AppTest.java.mustache",d,d)
    tpl(name,"{{project.name}}/pom.xml.mustache",d,d)

def spring():
    """ 
    me spring
    """
    name="spring"
    d=cfg(name)
    d["project"]["group_path"]=os.path.sep.join(d["project"]["group"].split("."))
    tpl(name,"{{project.name}}/src/main/java/{{project.group_path}}/{{project.artifact}}/App.java.mustache",d,d)
    tpl(name,"{{project.name}}/src/main/resources/application.yml.mustache",d,d)
    tpl(name,"{{project.name}}/src/test/java/{{project.group_path}}/{{project.artifact}}/AppTest.java.mustache",d,d)
    tpl(name,"{{project.name}}/pom.xml.mustache",d,d)

def maven():
    """ 
    me maven
    """
    name="maven"
    d=cfg(name)
    d["project"]["group_path"]=os.path.sep.join(d["project"]["group"].split("."))
    tpl(name,"{{project.name}}/src/main/java/{{project.group_path}}/{{project.artifact}}/App.java.mustache",d,d)
    tpl(name,"{{project.name}}/src/test/java/{{project.group_path}}/{{project.artifact}}/AppTest.java.mustache",d,d)
    tpl(name,"{{project.name}}/pom.xml.mustache",d,d)

def flask(command="new"):
    if command=="new":
        name="flask"
        project_name = input("Input your project name: ")
        cprint(project_name,"green")
        d={"project":{"name":project_name}}
        path, content=tpl(name,"{{project.name}}/app.py.mustache",d,d)
        cprint(path)
        knife.highlight(content)
    if command=="run":
        commands = [
        "setx FLASK_APP app.py",
        "setx FLASK_DEBUG 1",
        "setx FLASK_ENV development",
        'flask run --host=0.0.0.0',
        ]
        cmds(*commands)
    if command=="to":
        cmd("start http://127.0.0.1:5000")

def fastapi(command="new"):
    """
    me fastapi
    me fastapi new
    me fastapi run
    me fastapi to
    """
    if command=="new":
        name="fastapi"
        project_name = input("Input your project name: ")
        cprint(project_name,"green")
        d=cfg(name)
        d["project"]["name"] = project_name
        path, content=tpl(name,"{{project.name}}/app.py.mustache",d,d)
        tpl(name,"{{project.name}}/requirements.txt.mustache",d,d)
        cprint(path)
        knife.highlight(content)
    if command=="run":
        commands = [
        'python -m uvicorn app:app --reload --host 0.0.0.0 --port 8000',
        ]
        cmds(*commands)
    if command=="to":
        cmd("start http://127.0.0.1:8000")

def fab():
    write(os.path.join(os.getcwd(), "fabfile.py"),'''\
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import os
from fabric.api import local, lcd

def cwd():
    local(os.getcwd())
    ''')

def cfg(name,cfgfile="cfg.yml"):
    """
    me cfg maven
    """
    with codecs.open(os.path.join(os.getcwd(),cfgfile),'r',encoding='utf-8') as f:
        cfg=f.read()
        d=yaml.load(cfg, Loader=yaml.FullLoader)[name]
    knife.highlight(json.dumps(d, ensure_ascii=True,indent=2),"json")
    return d

def echo():
    s=input("请输入:")
    return s

def now():
    return knife.now_time_str()

def trans(q):
    """
    translate by youdao
    """
    return knife.translate(q)

def me():
    """
    安装命令me
    [o] python me.py me
    [x] me me
    """
    cmd("python setup.py install")

def main():
    # print(os.path.abspath(sys.argv[0]))
    fire.Fire()

if __name__ == '__main__':
    main()
